import tornado.ioloop
import tornado.web
import mysql.connector
import sys
import asyncio

if sys.platform == 'win32':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


def get_connect():
    cnx = mysql.connector.connect(user='root',
                                  password='[mysql]2021',
                                  host='127.0.0.1',
                                  port=3306,
                                  database='novel')
    return cnx


authors = []
books = {}
txt = []


class AuthorHandler(tornado.web.RequestHandler):
    def get(self):
        # todo
        # 1.链接mysql
        # 2.打开小说数据库
        # 3.Select 章节名 from 小说表
        items = []
        cnx = get_connect()
        cursor = cnx.cursor()
        query = ("SELECT distinct author FROM qzsd")
        cursor.execute(query)
        i = 0
        for au in cursor:
            items.append([i, au[0]])
            authors.append(au[0])
            i = i + 1
        cursor.close()
        cnx.close()
        self.render("author.html", title="作家列表", items=items)


class MenuHandler(tornado.web.RequestHandler):
    def get(self, aid):
        items = []
        cnx = get_connect()
        cursor = cnx.cursor()
        author = authors[int(aid)]
        books[author] = []
        query = ("SELECT distinct title FROM qzsd WHERE author=%s")
        cursor.execute(query, (author, ))
        i = 1
        for chap in cursor:
            items.append([i, chap[0], aid])
            books[author].append(chap[0])
            i = i + 1
        cursor.close()
        cnx.close()
        self.render("menu.html", title="{}作品".format(author), items=items)


class ChapterHandler(tornado.web.RequestHandler):
    def get(self, aid, bookid):
        cnx = get_connect()
        cursor = cnx.cursor()
        author = authors[int(aid)]
        book = books[author][int(bookid)]
        query = ("SELECT chapter FROM qzsd WHERE title=%s")
        cursor.execute(query, (book, ))
        chapinfo = {}
        items = []
        i = 0
        for chap in cursor:
            items.append([i, chap[0], aid, bookid])
            txt.append(chap[0])
            i = i + 1
        cursor.close()
        cnx.close()
        chapinfo['title'] = book
        chapinfo['content'] = items
        self.render("chapter.html", title=book, items=chapinfo)


class TextHandler(tornado.web.RequestHandler):
    def get(self, aid, bookid, chapid):
        cnx = get_connect()
        cursor = cnx.cursor()
        author = authors[int(aid)]
        book = books[author][int(bookid)]
        chapter = txt[int(chapid)]
        chapinfo = {}
        chapinfo["title"] = book
        query = ("SELECT text FROM qzsd WHERE chapter=%s")
        cursor.execute(query, (chapter, ))
        text = []
        for tt in cursor:
            text.append(tt[0])
        chapinfo["content"] = ''.join(text).split('\n')
        # break
        cursor.close()
        cnx.close()
        self.render("content.html", item=chapinfo)


def make_app():
    return tornado.web.Application([
        (r"/", AuthorHandler),
        (r"/([0-9]+)", MenuHandler),
        (r"/([0-9]+)/([0-9]+)", ChapterHandler),
        (r"/([0-9]+)/([0-9]+)/([0-9]+)", TextHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(7777)
    tornado.ioloop.IOLoop.current().start()